package com.icim.rest;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.icim.common.LoadHistoryConfig;
import com.icim.rabbitmq.util.RabbitmqManager;

@Controller
public class LoadHistoryMainController {

	private static Logger logger = Logger.getLogger(LoadHistoryMainController.class);

	private final static String _OKOKOK = "OKOKOK";
	private final static String _FAIL = "FAIL";
	private final static String END_PIXEL = "\r\n";

	@Autowired
	AmqpTemplate amqpTemplate;
	@Autowired
	LoadHistoryConfig loadHistoryConfig;
	@Autowired
	RabbitmqManager rabbitmqManager;

	@RequestMapping(value = "/healthcheck.do")
	public void healthcheck(HttpServletRequest request, HttpServletResponse response) {
		try {
			response.setContentType("application/json");
			PrintWriter pw = response.getWriter();
			boolean isUpRabbitMQ = checkRabbitMQ();
			boolean isUpDB = checkDB();
			if (isUpRabbitMQ & isUpDB) {
				pw.write(_OKOKOK);
			} else {
				pw.write(_FAIL);
			}
			pw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public boolean checkRabbitMQ() {
		return true;
	}

	public boolean checkDB() {
		return true;
	}

	@RequestMapping(value = "/sendHistoryMessage.do")
	public void sendHistoryMessage(HttpServletRequest request, HttpServletResponse response) {
		try {
			String queueName = request.getParameter("queue");
			String messsage = request.getParameter("message");
			if (messsage == null) {
				messsage = "===This is for test history message====";
			}
			rabbitmqManager.setMessage(queueName, messsage);
			response.setContentType("application/json");
			PrintWriter pw = response.getWriter();
			pw.write(_OKOKOK);
			pw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	

}
